﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Tokens;

namespace Lk.Api.JwtTokenAuth
{
    public class JwtHelper
    {

        public static string secretKey { get; set; } = "sdfsdfsrty45634kkhllghtdgdfss345t678fs";

        /// <summary>
        /// 颁发JWT字符串
        /// </summary>
        public static string IssueJwt(TokenModelJwt tokenModel)
        {
            var dateTime = DateTime.Now;
            var claims = new Claim[]
            {
              new Claim(JwtRegisteredClaimNames.Jti,tokenModel.Uid.ToString()),
              new Claim("Role",tokenModel.Role),
              new Claim("UserId",tokenModel.UserId.ToString()),
              new Claim(JwtRegisteredClaimNames.Iat,dateTime.ToString(),ClaimValueTypes.Integer64)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(issuer: "lk", claims: claims, expires: dateTime.AddHours(2), signingCredentials: creds);
            var jwtHandler = new JwtSecurityTokenHandler();
            var encodeJwt = jwtHandler.WriteToken(jwt);
            return encodeJwt;

        }

        /// <summary>
        /// 解析
        /// </summary>
        public static TokenModelJwt SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            object role = new object(); ;
            try
            {
                jwtToken.Payload.TryGetValue("Role", out role);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            var tm = new TokenModelJwt
            {
                Uid = long.Parse(jwtToken.Id),
                Role = role.ToString(),
            };
            return tm;
        }
    }

    public class TokenModelJwt
    {
        public long Uid { get; set; }

        public string Role { get; set; }

        //public string UserName { get; set; }
        //public string Pwd { get; set; }

        public Guid UserId { get; set; }
    }

}
